<?php

class CreateAction extends CAction
{
    private $_recipe;
    private $_steps=array();

    private function renderView()
    {
        $this->controller->render('create', array('recipe'=>$this->_recipe));    
    }
    
    private function validateImage()
    {
        if(!file_exists($this->_recipe->image->getTempName())) {
            $this->_recipe->addError('image','文件大小超过限制');
            return false;            
        }
        if(!UserImage::validateUploadFormat('recipe', $this->_recipe->image->getExtensionName())) {
            $this->_recipe->addError('image','文件格式不正确');
            return false;
        }
        return true;
    }
    
    public function run()
    {
        $this->_recipe=new Recipe;
        if(!isset($_POST['Recipe'])) {
            $this->renderView();
            return;
        }

        $this->_recipe->attributes=$_POST['Recipe'];
        $this->_recipe->userId=Yii::app()->user->id;
        $this->_recipe->userName=Yii::app()->user->name;
        $this->_recipe->image=CUploadedFile::getInstance($this->_recipe,'image');
        if($this->_recipe->image) {
            if(!$this->validateImage()) {
                $this->renderView();
                return;                                
            }
            else {
                $this->_recipe->image=UserImage::create('recipe', $this->_recipe->image->getTempName());
                if($this->_recipe->image===false) {
                    $this->_recipe->addError('image','保存文件失败，请检查文件格式是否正确');
                    $this->renderView();
                    return;                    
                }
            }
        }

        try {
            $succ=Recipe::saveObject($this->_recipe);
        }
        catch(Exception $e){
            UserImage::delete('recipe',$this->_recipe->image);
            throw $e;
        }        

        if(!$succ) {
            if($this->_recipe->image) {
                UserImage::delete('recipe',$this->_recipe->image);
            }
            $this->renderView();
        }
        else {
            $this->controller->redirect(array('show','id'=>$this->_recipe->id));        
        }        
    }
}

?>